package com.yyplatform.admin.infra.web.shiro;


import com.yyplatform.admin.infra.model.dto.RequestInfoDTO;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yyplatform.admin.infra.utils.RequestUtils;
import com.yyplatform.admin.infra.utils.JsonUtils;
import com.yyplatform.admin.infra.utils.RequestInfoUtils;
import com.yyplatform.admin.infra.exception.ErrorCode;
import com.yyplatform.admin.infra.model.RestResponse;

import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtShiroFilter extends AuthenticatingFilter {


    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse)
            throws Exception {
        String token = getRequestToken((HttpServletRequest) servletRequest);

        if (StringUtils.isBlank(token)) {
            return null;
        }

        return new JwtShiroToken(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) servletRequest).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }

        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        if (StringUtils.isBlank(token)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setContentType("application/json;charset=utf-8");
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", RequestUtils.getOrigin((HttpServletRequest) request));

            RestResponse<RequestInfoDTO> r = RestResponse.of(ErrorCode.UNAUTHORIZED);
            r.setData(RequestInfoUtils.build((HttpServletRequest) request));

            String json = JsonUtils.toJsonString(r);

            httpResponse.getWriter().print(json);

            return false;
        }

        return executeLogin(request, response);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
            ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", RequestUtils.getOrigin((HttpServletRequest) request));
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            RestResponse<RequestInfoDTO> r = RestResponse.of(ErrorCode.UNAUTHORIZED.getCode(), throwable.getMessage());

            r.setData(RequestInfoUtils.build((HttpServletRequest) request));


            String json = JsonUtils.toJsonString(r);
            httpResponse.getWriter().print(json);
        } catch (Exception e1) {
            log.error(e1.getMessage(), e1);
        }


        return false;
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader(JwtShiroToken.JWT_TOKEN_NAME);

        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter(JwtShiroToken.JWT_TOKEN_NAME);
        }

        return token;
    }


}
